package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import javax.servlet.http.Cookie;

import bean.User;
import dao.UserDAO;

@WebServlet(name = "LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = new UserDAO().getUser(username);

        HttpSession session = req.getSession();

        if (user.getUsername() == null){//若用户不存在
            req.setAttribute("flag","null");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }else {
            if ( password.equals(user.getPassword()) ){
                //登陆成功
                session.setAttribute("username",username);//将用户名用于session域进行权限检查
                System.out.println("登陆成功！session："+session.getAttribute("username"));

                if (username!=null){
                    Cookie c = new Cookie("user",username);
                    c.setMaxAge(60);//有效时间60s
                    resp.addCookie(c);//将Cookie对象保存到客户端
                }

                resp.sendRedirect("/StuSystem_war_exploded/ListServlet");
            }else {
                req.setAttribute("flag","false");
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }
        }
    }
}
